package com.hl.glidedemo.ui

import android.content.res.Configuration
import android.graphics.drawable.Drawable
import android.graphics.drawable.InsetDrawable
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.hl.glidedemo.data.const.UrlConst
import com.hl.glidedemo.databinding.ActivityMainBinding
import com.hl.glidedemo.util.GlideUtil
import com.hl.glidedemo.worker.MyWork
import com.hl.lib.views.NoPaddingTextView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response


class MainActivity : AppCompatActivity() {

    companion object {
        val TAG = MainActivity::class.java.simpleName
    }

    private lateinit var handler: Handler
    private lateinit var binding: ActivityMainBinding
    private val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        handler = Handler(Looper.getMainLooper())

        loadView()

        val options = RequestOptions()
            .override(25, 25 ) // 设置图片的目标大小
        // 使用Glide加载图片，并在加载完成后进行处理


        Glide.with(this)
            .load("https://www.25h.net/d/file/20230623/e112817eaa44942a0bf81f7e0163ed28.jpg") // 替换为您的图片URL
            .apply(options)
            .into(object : CustomTarget<Drawable>() {

                override fun onResourceReady(
                    resource: Drawable,
                    transition: Transition<in Drawable>?
                ) {
                    resource.setBounds(0, 0, 25, 25                    )
                    // 创建InsetDrawable，添加左边距
                    val leftInset = 50 // 设置左边距为16dp
                    val insetDrawable = InsetDrawable(resource, leftInset, 0, 0, 0)

                    // 设置TextView的drawableStart
                    binding.button1.setCompoundDrawablesRelativeWithIntrinsicBounds(null, insetDrawable, null, null)
                }

                override fun onLoadCleared(placeholder: Drawable?) {
                    // 当加载被清除时（例如，由于ImageView被重用），可以在这里处理清除逻辑
                }
            })


        lifecycleScope.launchWhenStarted {
            val result = withContext(Dispatchers.IO) {
                delay(1000)
            }
            (binding.tvText as NoPaddingTextView).text = "请求完毕请求完毕请求完毕请求完毕"
        }

        lifecycleScope.launch(Dispatchers.Main) {
            val response = withContext(Dispatchers.IO) {
                makeNetworkCall()
            }

            if (response.isSuccessful) {
                val body = response.body?.string()
                // 更新UI
                updateUi(body)
            } else {
                // 处理错误
                handleError(response.code.toString())
            }
        }
    }

    private suspend fun makeNetworkCall(): Response {
        val request = Request.Builder()
            .url("https://your-api-url.com/endpoint")
            .build()

        return withContext(Dispatchers.IO) {
            client.newCall(request).execute() // 这里会阻塞当前协程，直到收到网络响应
        }
    }

    private fun updateUi(data: String?) {
        // 更新UI组件
        // 示例：textView.text = data
    }

    private fun handleError(errorMessage: String) {
        // 显示错误信息或处理异常
    }


    private fun loadView() {
        handler.post {

            // 使用Glide加载图片到View的背景
            GlideUtil.setBackground(binding.ctlMain, UrlConst.imageUrl1)
            GlideUtil.setBackground(binding.tvText, UrlConst.imageUrl2)
            GlideUtil.setSrc(binding.ivPicture, UrlConst.imageUrl3)

            val workRequest = OneTimeWorkRequestBuilder<MyWork>().build()
            WorkManager.getInstance(this).enqueue(workRequest)
//            WorkManager.getInstance(this).enqueue(OneTimeWorkRequestBuilder<MyWork1>().build())
//            WorkManager.getInstance(this).enqueue(OneTimeWorkRequestBuilder<MyWork2>().build())

        }
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        loadView()

        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 处理横屏逻辑
            Log.e(TAG, "onConfigurationChanged: 切换到横屏")
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            // 处理竖屏逻辑
            Log.e(TAG, "onConfigurationChanged: 切换到竖屏")
        }
    }

}